package org.supreme.fegin;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
@Component
public class loginFegin extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        //获取上下文路径
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取里面的请求
        HttpServletRequest request = currentContext.getRequest();
        // 1.获取请求地址
        String requestURI = request.getRequestURI();
        //判断当前请求是否为空
        if (requestURI.endsWith("login") || requestURI.endsWith("register") ){
            return false;
        }
       return true;
    }

    @Override
    public Object run() throws ZuulException {
        //获取上下文路径
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //获取到请求头里面的请求
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();
        //设置字符集
        response.setContentType("application/json;charset=utf-8");
        // 2.判断是否包含token，如果不包含，那么需要阻止执行后面的filter，并且还要返回错误信息，提示用户登录
        String token = request.getHeader("token");
        // 2.1.判断token为空，那么需要提示用户，并且阻止filter执行
        if (!StringUtils.isEmpty(token)){
            try {
                PrintWriter writer = response.getWriter();
                HashMap<String, Object> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.put("success", false);
                objectObjectHashMap.put("message", "登录校验失败，请重新登录！");
                String s = JSON.toJSONString(objectObjectHashMap);
                    writer.write(s);
                // 2.阻止后续filter执行
                RequestContext.getCurrentContext().setSendZuulResponse(false);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        // 如果要放行，这里返回null即可，不用管
        return null;
    }
}
